<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button class="btn">点我++(throttle)</button>
  <button class="btn2">点我++(debounce)</button>
  <button class="btn3">点我++(debounce & throttle)</button>
  <script>
    const btn = document.querySelector('.btn');
    const btn2 = document.querySelector('.btn2');
    const btn3 = document.querySelector('.btn3');
    const addT = throttle(add, 1000);
    const addD = debounce(add, 1000);
    const addTD = throttleAndDebounce(add, 1000);

    btn.addEventListener('click', () => {
      addT(1, 2);
    })

    btn2.addEventListener('click', () => {
      addD(1, 2);
    })

    btn3.addEventListener('click', () => {
      addTD(1, 2);
    })

    // 函数节流
    function throttle(fn, timeStep) {
      let prevTime = Date.now()

      return function (...args) {
        let now = Date.now()
        if (now - prevTime < timeStep) {
          return
        } else {
          console.log(args);
          fn.apply(this, args)
          prevTime = now
        }
      }
    }

    function add(a, b) {
      console.log(a + b);
    }


    // 函数防抖
    function debounce(fn, timeStep) {
      let time;
      return function (...args) {
        if (time) {
          clearTimeout(time)
        }
        time = setTimeout(() => {
          fn.apply(this, args)
        }, timeStep)
      }
    }

    // 节流防抖结合
    function throttleAndDebounce(fn, timeStep) {
      let prevTime = Date.now()
      let time = null;

      return function (...args) {
        let now = Date.now()
        if (now - prevTime < timeStep) {
          clearTimeout(time);
          time = setTimeout(() => {
            prevTime = now;
            fn.apply(this, args)
          },timeStep)
        } else {
          prevTime = now;
          fn.apply(this, args)
        }
      }
    }
  </script>
</body>

</html>